<template>
  <div class="user_container">
    <el-card shadow="always" v-loading="userTableLoading" :body-style="{ padding: '10px' }">
      <el-row :gutter="10">
        <!-- span一行最大24 是一整行的长度 gutter是指定的没干elcol之间的距离 offset是偏移的栏数 -->
        <el-col :span="6" :offset="0">
          <el-input v-model="queryInfo.searchTerm" type="text" size="default" clearable placeholder="请输入用户名" prefix-icon="Search" :input-style="{}" @clear="getUserTableList">
            <template #append>
              <el-button icon="Search" size="default" @click="getUserTableList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-button type="primary" icon="Plus" size="default" @click="addUser" v-if="isHasPermission('add')">添加用户</el-button>
          <el-button type="primary" icon="Delete" size="default" @click="deleteUser" v-if="isHasPermission('delete')">删除用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" v-loading="userTableLoading" ref="tableRef" @sort-change="userSortChanged" @selection-change="handleSelectionChange" size="small" highlight-current-row stripe border style="width: 100%" element-loading-text="Loading..." element-loading-svg-view-box="-10, -10, 50, 50" element-loading-background="rgba(0, 0, 0, 0.8)">
        <!-- label列名  propd对应对象中的key -->
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" :index="computeIndex" width="50" label="序号" />
        <el-table-column prop="userName" label="用户名" width="180" sortable />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phoneNumber" label="电话号码" width="180" />
        <el-table-column prop="crteTime" label="创建时间" width="180" />
        <el-table-column prop="isActive" label="是否启用" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.isActive" @change="changeActiveState(scope.row)" class="ml-2" active-color="#13ce66" inactive-color="#ff4949" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" icon="Edit" type="primary" @click="showEditDialog(scope.$index, scope.row)" v-if="isHasPermission('edit')">编辑</el-button>
            <el-button size="small" icon="User" type="warning" @click="showAllotRoleDialog(scope.$index, scope.row)" v-if="isHasPermission('allot')">分配角色</el-button>
            <el-button size="small" icon="Delete" type="danger" @click="deleteUserByIds(scope.$index, scope.row)" v-if="isHasPermission('delete')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :currentPage="pageInfo.pageIndex" v-model:page-size="pageInfo.pageSize" :total="pageInfo.totalCount" :page-sizes="[5, 10, 50, 100]" @size-change="handleSizeChange" @current-change="handleCurrentChange" small background layout="total, sizes, prev, pager, next, jumper"> </el-pagination>
    </el-card>
  </div>
  <user-dialog :visible="addDialogVisible" :isCreate="isCreate" :userForm="userUpdateInfo" @closeUserAdd="closeUserAdd" @refreshUserList="refreshUserList"></user-dialog>
  <allot-user-role :visible="allotUserRoleVisible" :userInfo="userInfo" :roleList="roleList" @closeRoleDialog="closeRoleDialog"></allot-user-role>
</template>
<script>
export default {
  name: "User",
};
</script>
<script setup>
import { getCurrentInstance, ref, reactive, onMounted, onUnmounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { messageUtils } from "assets/js/messageUtils.js";
import { getUserList, patchUser, deleteUsers, getUserInfo, getUserRoleList } from "network/user.js";
import { PaginationData } from "@/model/dataModel.js";
import UserDialog from "./UserDialog";
import AllotUserRole from "./AllotUserRole";
import { isHasPermission } from "assets/js/directives/permission.js";

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();

let userTableLoading = ref(false);
//这边指示动态绑定了对象  还是要等组件挂载好了才能获取tableRef的值
//所以要再mounted中使用
const tableRef = ref(null);
//用户列表
let userList = ref([]);
//查询信息
let queryInfo = reactive({
  searchTerm: "",
  pageIndex: 1,
  pageSize: 10,
});
//分页信息
let pageInfo = reactive(new PaginationData(1, 5, 0));
//选中行数据
let selectedRows = ref([]);
//添加用户的对话框
let addDialogVisible = ref(false);
//分配用户角色的对话框
let allotUserRoleVisible = ref(false);
let isCreate = ref(false);
let userUpdateInfo = ref({
  userName: "",
  password: "",
  email: "",
  phoneNumber: "",
});
let userInfo = ref({});
let roleList = ref([]);

const getUserTableList = async () => {
  userTableLoading.value = true;
  const res = await getUserList(queryInfo);
  if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
  proxy.$notify.success({ message: res.msg, showClose: true });
  userList.value = res.response;
  userTableLoading.value = false;
  pageInfo.pageIndex = res.pageIndex;
  pageInfo.pageSize = res.pageSize;
  pageInfo.totalCount = res.totalCount;
};
onMounted(() => {
  getUserTableList();
});
//分页条pageSize变化时
const handleSizeChange = (newSize) => {
  queryInfo.pageSize = newSize;
  getUserTableList();
};
//分页条pageIndex变化时
const handleCurrentChange = (newIndex) => {
  queryInfo.pageIndex = newIndex;
  getUserTableList();
};
//更改用户活跃状态
const changeActiveState = async (row) => {
  let patchDocument = reactive([{ op: "add", path: "/isActive", value: row.isActive }]);
  const res = await patchUser(row.id, patchDocument);
  if (!res.success) {
    proxy.$notify.error({ message: res.msg, showClose: true });
    row.isActive = !role.isActive;
  }
  proxy.$notify.success({ message: res.msg, showClose: true });
};

const computeIndex = (index) => {
  return (pageInfo.pageIndex - 1) * pageInfo.pageSize + index + 1;
};
//给表格排序
const userSortChanged = (column, prop, order) => {
  console.log(column, prop, order);
};
//选中行改变时触发
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};
//删除用户
const deleteUser = async () => {
  if (selectedRows.value.length <= 0) return proxy.$notify.error({ message: "请选择要删除的数据", showClose: true });

  let selectedIds = selectedRows.value.map((c) => c.id);
  messageUtils.ElMessageBoxDeleteTips(deleteUsers, getUserTableList, proxy, selectedIds);
};
//根据id删除用户
const deleteUserByIds = (index, row) => {
  let id = [];
  id.push(row.id);
  messageUtils.ElMessageBoxDeleteTips(deleteUsers, getUserTableList, proxy, id);
};
//添加用户
const addUser = () => {
  isCreate.value = true;
  addDialogVisible.value = true;
};
//关闭添加用户的对话框
const closeUserAdd = () => {
  addDialogVisible.value = false;
  userUpdateInfo.value = ref({});
};
//添加完成,刷新列表
const refreshUserList = () => {
  getUserTableList();
};
//编辑用户
const showEditDialog = async (index, row) => {
  const res = await getUserInfo(row.id);
  if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
  userUpdateInfo.value = res.response;
  isCreate.value = false;
  addDialogVisible.value = true;
};
//展示分配用户角色的对话框
const showAllotRoleDialog = async (index, row) => {
  const res = await getUserRoleList(row.id);
  if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
  userInfo.value = row;

  roleList.value = res.response;
  allotUserRoleVisible.value = true;
};
//关闭分配角色的对话框
const closeRoleDialog = () => {
  allotUserRoleVisible.value = false;
};
</script>
<style lang="less" scoped></style>
